<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Hello, world!</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="../css/font-awesome.min.css">
    <link rel="stylesheet" href="../css/bootstrap.min.css">
    <link rel="stylesheet" href="../fonts/iconfont.css">
    <link rel="stylesheet" href="../css/bootstrap-select.min.css">
    <link rel="stylesheet" href="../css/select2.min.css">
    <link rel="stylesheet" href="../css/select2-bootstrap4.min.css">

    <link rel="stylesheet" href="../css/style.css">
    <style>
        .bd-placeholder-img {
            font-size: 1.125rem;
            text-anchor: middle;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
        }

        @media (min-width: 768px) {
            .bd-placeholder-img-lg {
                font-size: 3.5rem;
            }
        }

        html,
        body {
            height: 100%;
        }

        .wareContent{
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
        }
       
        body {
            padding-bottom: 40px;
            background-color: #fff;
        }

        .form-signin {
            width: 100%;
            max-width: 640px;
            margin: auto;
            padding: 15px;
        }

        .form-signin .checkbox {
            font-weight: 400;
        }

        .form-signin .form-control {
            position: relative;
            box-sizing: border-box;
            height: auto;
            padding: 10px;
            font-size: 16px;
        }

        .form-signin .form-control:focus {
            z-index: 2;
        }

        .form-signin input[type="email"] {
            margin-bottom: -1px;
            border-bottom-right-radius: 0;
            border-bottom-left-radius: 0;
        }

        .form-signin input[type="password"] {
            margin-bottom: 10px;
            border-top-left-radius: 0;
            border-top-right-radius: 0;
        }

        .sr-only2 {
            margin-top: 15px;
        }


        .logodiv img {
            width: 240px;
            margin: 0 auto;
            display: block;
        }

        .logodiv {
            text-align: center;
        }

        .logodiv h1 {
            font-size: 1.4rem;
            color: #03357a;
            margin-top: 20px;
            margin-bottom: 20px;
        }

        .logodiv h2 {
            font-size: 1.5rem;
            margin-bottom: 80px;
        }



        .fgtpaws {
            text-align: center;
            margin-top: 10px;
        }

        .btn {
            padding: 0.375rem 0.15rem
        }

        .btn-tiqu {
            width: 125px;
            margin: 0 auto;
            display: block;
        }

        .buytitle {
            font-size: 1.1rem;
            color: #03357a;
            margin-top: 20px;
        }

        .buytitle span {
            font-size: 1rem;
            color: #999;
        }
        #app{
            height: 100vh;
            overflow: hidden;
        }

        .action-row button {
            margin-bottom: 10px;
        }

        .buysearch {
            font-size: smaller;
        }

        .formscreen .form-control-theme {
            font-size: smaller;
        }

        .action-row {
            position: fixed;
            width: 100%;
            bottom: 0;
            margin-top: 0;
            margin-bottom: 0;
            background: #fff;
            left: 0;
        }

        .container2 {
            padding: 10px;
            height: 100vh;
            display: block;
        }

        .bootstrap-select {
            width: calc(100% - 0px) !important;
        }

        .formscreen .filter-option-inner-inner {
            font-size: smaller;
        }

        .myselect {
            width: calc(100% - 0px);
        }

        .btn-action:disabled {
            background: #D9D9DA !important;
            color: #808081 !important;
        }

        .buysearch {
            width: 100%;
            display: block;
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="container2">



            <div class="modal fade fullmodal show" v-if="screenwidth<576" style="display: block;" id="exampleModal"
                tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-body">
                            <div class="logodiv">
                                <img class="bannerlogo pt-3" src="../image/logo.jpeg">
                                <h3 class="mt-3 mb-5">{{lan['Misc_Issue']}}</h3>
                            </div>
                            <div class="row  align-items-center">


                                <div class="col-12 col-sm-6 col-md-3">
                                    <div class="d-flex bd-highlight align-items-center">
                                        <div class="p-2 bd-highligh flex-shrink-0 filedlabel">{{lan['REASON_CODE']}}
                                        </div>
                                        <div class="p-2 flex-grow-1 bd-highlight">
                                            <select v-model="searchdata.ReasonCode"
                                                class="js-data-example-ajax"></select>
                                        </div>
                                    </div>
                                </div>



                                <div class="col-12 col-sm-6 col-md-3">
                                    <div class="d-flex bd-highlight align-items-center">
                                        <div class="p-2 bd-highligh  flex-shrink-0 filedlabel">{{lan['Issue_Date']}}
                                        </div>
                                        <div class="p-2 flex-grow-1 bd-highlight">
                                            <input type="date" v-model="searchdata.ArrivedDate"
                                                placeholder="Please Enter Issue Date(Required)"
                                                class="form-control form-control-theme" value="">
                                        </div>
                                    </div>
                                </div>




                                <div class="col-12">
                                    <div class="d-flex bd-highlight align-items-center">
                                        <div class="p-2 bd-highligh flex-shrink-0 filedlabel">{{lan['User']}}</div>
                                        <div class="p-2 flex-grow-1 bd-highlight">
                                            <input type="text" v-model="searchdata.name" disabled
                                                class="form-control form-control-theme" value="">
                                        </div>
                                    </div>
                                </div>


                            </div>

                            <div class=" row justify-content-center mt-4">
                                <div class="col-4 col-md-4">
                                    <button type="button" @click="hidemodal()" tapmode=""
                                        class="btn btn-primary btn-action">{{lan['OK']}}</button>
                                </div>


                                <div class="col-4 col-md-4">
                                    <button type="button" tapmode="" onclick="close_win()"
                                        class="btn btn-primary btn-action">{{lan['Cancel']}}</button>
                                </div>

                            </div>

                        </div>

                        <div class="modal-footer">
                            <div class="copyright">
                                <div class="row" :gutter="10">
                                    <div  class="col-5" style="text-align: right;">{{lan['Version']}}：</div>
                                    <div  class="col-7">{{appversion}}</div>
                                    <div  class="col-5"  style="text-align: right;">{{lan['Site']}}：</div>
                                    <div  class="col-7">{{SiteName}}</div>
                                    <div  class="col-5"  style="text-align: right;">{{lan['Company']}}：</div>
                                    <div  class="col-7">{{CompanyName}}</div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        
            <div class="buysearch buysearch2">
                <div  class="row   align-items-center">

                    <div class="col-12 col-sm-12 col-md-12">
                        <table class="table table-buy table-borderless table-sm">
                            <tr>
                                <td class="ttl">{{lan['Issue_Date']}}</td>
                                <td class="ttl"></td>
                            </tr>
                            <tr>
                                <td> {{searchdata.ArrivedDate}}</td>
                                <td></td>
                            </tr>
                        </table>
                    </div>
                </div>

            </div>

            <div class="row">
                <div v-for="(item,index) in list" :key="index"  class="col-12 col-sm-12 col-md-12">
                    <table class="table table-buy table-borderless table-sm">
                        <tr>
                            <td class="ttl" colspan="2">{{lan['Part']}}/{{lan['Desc']}}</td>
                            <td></td>
                        </tr>
                        <tr>
                            <td colspan="2">{{item.PartNum}}<br />{{item.PartDescription}}</td>
                            <td><i v-if="!Lot_btn" @click="remove(item,index)" class="iconfont icon-delete"></i></td>
                        </tr>
                        <tr>
                            <td style="width: 33%;" class="ttl">{{lan['WareHouseCode']}}</td>
                            <td  style="width: 33%;" class="ttl"></td>
                            <td  style="width: 33%;" class="ttl">{{lan['BinNum']}}</td>
                        </tr>
                        <tr>
                            <td  style="width: 33%;">
                                <div class="wareContent">
                                    <input   v-if="!list[index].warehouseFlag" type="text"
                                    :disabled = "Lot_btn"
                                    v-model="list[index].WareHouseCode"
                                    @click="warehouseFocus(item,index)"
                                    class="form-control form-control-num" value="">
                                    <select :disabled = "Lot_btn"  v-if="list[index].warehouseFlag" @change="binNumChange(item,index)"  v-model="list[index].WareHouseCode" 
                                        class="form-control"    data-live-search="true">
                                        <option v-for="(item2,index2) in list[index].WareHouseCodeList" :key="index2" 
                                            :value="item2.Warehse_WarehouseCode" :data-name="item2.Warehse_WarehouseCode">
                                            {{item2.Warehse_WarehouseCode}}</option>
                                    </select>
                                    <i v-if="!list[index].warehouseFlag" style="margin-left: 5px;" @click="onWareQuery(item,index)" class="iconfont icon-scan"></i>
                                    <i v-if="list[index].warehouseFlag" style="margin-left: 5px;" @click="onWareScan(item,index)" class="iconfont icon-query"></i>
                                </div>
                               
                            </td>
                            <td  style="width: 33%;"></td>
                            <td  style="width: 33%;">
                                <div class="wareContent">
                                    <input   v-if="!list[index].binFlag" type="text"
                                    @click="binFocus(item,index)"
                                    :disabled = "Lot_btn"
                                    v-model="list[index].BinNum"
                                    class="form-control form-control-num" value="">
                                    <select :disabled = "Lot_btn"  v-if="list[index].binFlag"  @change="OnNumChange(item,index)"   v-model="list[index].BinNum" 
                                        class="form-control" data-live-search="true">
                                        <option v-for="(item2,index2) in list[index].BinNumList" :key="index2"  :value="item2.WhseBin_BinNum" >
                                            {{item2.WhseBin_BinNum}}
                                        </option>
                                    </select>
                                    <i  v-if="!list[index].binFlag" style="margin-left: 5px;" @click="onBinQuery(item,index)" class="iconfont  icon-scan"></i>
                                    <i  v-if="list[index].binFlag" style="margin-left: 5px;" @click="onBinScan(item,index)" class="iconfont icon-query"></i>
                                </div>
                              
                            </td>
                        </tr>
                        <tr>
                            <td  style="width: 33%;" class="ttl">{{lan['Lot']}}</td>
                            <td  style="width: 33%;" class="ttl">{{lan['Qty']}}</td>
                            <td  style="width: 33%;" class="ttl"></td>
                        </tr>
                        <tr>
                            <td>
                                <div class="wareContent">

                                    <input  type="number"
                                    v-if="item.lotFlag"
                                    @blur="lotBlur(item,index)"
                                    :disabled="!item.Part_TrackLots || receipt_btn"
                                    v-model="item.LotNum"
                                    class="form-control form-control-num" value="">
                                    <input  type="number"
                                    v-if="!item.lotFlag"
                                    :disabled="!item.Part_TrackLots || receipt_btn"
                                    @click="lotFocus(item,index)"
                                    v-model="item.LotNum"
                                    class="form-control form-control-num" value="">
                                    <i  v-if="!item.lotFlag" style="margin-left: 5px;" @click="onLotQuery(item,index)" class="iconfont  icon-scan"></i>
                                    <i  v-if="item.lotFlag" style="margin-left: 5px;" @click="onLotScan(item,index)" class="iconfont icon-query"></i>

                                </div>

                            </td>
                            <td class="ttl">
                                <div style="display: flex;align-items: center;">
                                    <input  type="number"
                                    @input="checkDecimal(index,item)"
                                    @change="checkNum(index,item)" 
                                    :step="item.AllowDecimals ? 'any' : '1'"
                                    v-model="list[index].OnhandQty"
                                    :disabled="receipt_btn"
                                    class="form-control form-control-num" value="">
                                    <span style="width: 20px;margin-left:2px;display: inline-block;">{{item.IUM}}</span>
                                </div>
                            </td>
                     
                            <td class="ttl">
                                <button style="width: 100px;" type="button" tapmode="" @click="toSerial(index,item)" :disabled="!list[index].Part_TrackSerialNum"
                                :class=" list[index].Part_TrackSerialNum == false ? 'btn-secondary':'btn-primary'"
                                class="btn   btn-block">{{lan['Serial_No']}} <span
                                    class="badge badge-light">{{item.SerialNum.length}}</span>
                                </button>
                            </td>
                        </tr>
                        
                    </table>
                </div>
            </div>


        </div>
        <div class="action-row">
            <div class="container">
                <div class=" row justify-content-center">
                    <div class="col-3 col-md-3">
                        <button type="button" onclick="scan();" tapmode=""
                            class="btn btn-primary btn-action">{{lan['Scan']}}
                        </button>
                    </div>
                    <div class="col-3 col-md-3">
                        <button type="button" tapmode="" :disabled="receipt_btn" onclick="checksubmit();"
                            class="btn btn-primary btn-action">{{lan['Comfirm']}}</button>
                    </div>
                    <div class="col-3 col-md-3">
                        <button type="button" tapmode="" :disabled="list.length == 0 " onclick="resetfrom();"
                            class="btn btn-primary btn-action">{{lan['Reset']}}</button>
                    </div>
                    <div class="col-3 col-md-3">
                        <button type="button" tapmode="" onclick="close_win1()"
                            class="btn btn-primary btn-action">{{lan['Cancel']}}
                        </button>
                    </div>

                </div>

            </div>

        </div>
    </div>

</body>
<script type="text/javascript" src="../script/lang.js"></script>
<script type="text/javascript" src="../script/model.js"></script>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/vue.min.js"></script>
<script type="text/javascript" src="../script/jquery.min.js"></script>
<script type="text/javascript" src="../script/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src="../script/bootstrap-select.min.js"></script>
<script type="text/javascript" src="../script/select2/select2.min.js"></script>
<script type="text/javascript" src="../script/common.js"></script>
<script type="text/javascript">
    var postcount = 0;
    var tagspostcount = 0;
    var returncount = 0;
    var postlist = [];
    var tags = [];

    const app = new Vue({
        el: '#app',
        data: {
            list: [],
            listids: [],
            inOutData:{},
            screenwidth: document.body.clientWidth,
            vendors: [],
            RowNum:1,
            searchdata: {
                name: '',
                PackSlip: '',
                ArrivedDate: timenow(),
                ReasonCode: '',
                PartNum:'',
                BinNum:'',
                LotNum:'',
            },
            uinfo: {},
            outinfo:{},
            currentData:{},
            lotinfo: {},
            create_btn: false,
            confirm_btn:false,
            receipt_btn: true,
            print_btn: true,
            snsCheck:false,
            Lot_btn:false,
            print_num: '',
        },
        mounted() {
            const that = this
            window.onresize = () => {
                return (() => {
                    that.screenwidth = document.body.clientWidth
                })()
            }
            this.showmodal();
            init_select2();
            //init_select();
        },

        methods: {
            binNumChange(item,index) {
                loadBinData(item,index)
            },
            remove: function (item,index) {
                this.list.splice(index, 1);
                if(this.list.length == 0){
                    this.receipt_btn = true;
                    this.Lot_btn = false;
                }
                
            },
            warehouseFocus:function(item,index){
                setTimeout(function(){
                    scan2(item,index)
                },100)
            },
            binFocus:function(item,index){
                if(item.WareHouseCode == ""){
                    api.toast({
                        msg: lan['WareHouseCode_placeholder'],
                        location: 'middle'
                    });
                    return;
                }
                setTimeout(function(){
                    scan3(item,index)
                },100)
            },
            lotFocus:function(item,index){
                if(item.WareHouseCode == ""){
                    api.toast({
                        msg: lan['WareHouseCode_placeholder'],
                        location: 'middle'
                    });
                    return;
                }
                if(item.BinNum == ""){
                    api.toast({
                        msg: lan['BinNum_placeholder'],
                        location: 'middle'
                    });
                    return;
                }
                setTimeout(function(){
                    scan1(item,index)
                },100)
            },
            onLotQuery(item,index){
                item.lotFlag = true;
            },
            onLotScan(item,index){
                item.lotFlag = false;
            },
            onWareQuery(item,index){
                item.warehouseFlag = true;
            },
            onWareScan(item,index){
                item.warehouseFlag = false;
            },
            onBinQuery(item,index){
                item.binFlag = true;
            },
            onBinScan(item,index){
                item.binFlag = false;
            },
            lotBlur:function(item,index){
                if(item.WareHouseCode == ""){
                    api.toast({
                        msg: lan['WareHouseCode_placeholder'],
                        location: 'middle'
                    });
                    return;
                }
                if(item.BinNum == ""){
                    api.toast({
                        msg: lan['BinNum_placeholder'],
                        location: 'middle'
                    });
                    return;
                }
                onHandData(item,index)
            },
            OnNumChange(item,index){
                onHandData(item,index)
            },
            checkDecimal(index, item) {
                if(item.Part_TrackLots && item.LotNum == ""){
                    api.toast({
                        msg: lan['LotNum_placeholder'],
                        location: 'middle'
                    });
                    item.OnhandQty=""
                    return;
                }
                // 获取输入的值
                let inputValue = item.OnhandQty;

                // 将输入值解析为浮点数
                let parsedValue = parseFloat(inputValue);

                // 如果解析成功，限制小数位数不超过 NumOfDec
                if (!isNaN(parsedValue)) {
                    const decimalCount = (inputValue.toString().split('.')[1] || "").length || 0;
                    if (decimalCount > item.NumOfDec) {
                        // 超过 NumOfDec 位小数，截取前 NumOfDec 位小数，不进行四舍五入
                        inputValue = inputValue.substring(0, inputValue.indexOf('.') + item.NumOfDec + 1);
                    }
                    item.OnhandQty = inputValue;
                }
            },
            toSerial: function (index, item) {
                var data = {};
                item.SerialNum = []
                var InputOurQty = processNumber(item.OnhandQty, item.NumOfDec);
                for (let i = 0; i < InputOurQty; i++) {
                    item.SerialNum.push({
                        'type': i+1,
                        'SerialNumber': '',
                    })
                }
                data.post = item;
                data.index = index;
                data.post.snsCheck = app.snsCheck
                data.post.index = index;
                data.searchdata = this.searchdata;
                data.title = lan['Misc_Issue'];
                data.right = [{
                    text: lan["Scan"],
                    color: '#fff',
                }];
                data.frame = "sn_job_issue";

                console_debug(data,"sn_job_issue");

                openNavWin2(data.frame, data);

            },
           
            showmodal: function () {
                if (this.screenwidth < 576) {
                    $('#exampleModal').modal('show');
                    //init_select();
                } else {

                    $('#PackSlip').focus();
                }
            },
            checkNum: function (index, item) {
                var OnhandQty = processNumber(this.list[index].OnhandQty,this.list[index].NumOfDec) ? processNumber(this.list[index].OnhandQty,this.list[index].NumOfDec) : 0;
                if (OnhandQty <= 0) {
                    OnhandQty = 1;
                }
               
                this.$set(this.$data.list[index], 'OnhandQty', OnhandQty);
                //this.calc_total();
                this.receipt_btn = false;
            },
           
            hidemodal: function () {
                if (this.searchdata.ReasonCode == '') {
                    api.toast({
                        msg: lan['REASON_CODE_placeholder'],
                        location: 'middle'
                    });
                    return;
                }
                app.confirm_btn = true
                $('#exampleModal').modal('hide');
            },
        }
    });
    apiready = function () {
        api.parseTapmode();
        server = getapi();
        back_listen();
        app.vendors = get_prefs_data("Vendors");
        app.uinfo = get_user_info();
        userinfo = get_user_info();

        app.searchdata.name = userinfo.Name;
        api.addEventListener({
            name: 'infrared_scanning'
        }, function (ret, err) {
            console.log(JSON.stringify(ret));
            if (ret && ret.value && ret.value.str && is_scan == 0) {
                loadqrData(ret.value.str);
            }

        });
        api.addEventListener({
            name: 'keyback',
            extra: {
                slidBackIntercept: true    
            }
        }, function (ret, err) {
            if(app.confirm_btn){
                close_win1()  
            }else{
                close_win()
            }   

        });
        api.addEventListener({ name: 'navitembtn' }, function (ret, err) {
            if (ret.type == 'left') { 
            
                if(app.confirm_btn){
                    close_win1()  
                }else{
                    close_win()
                }    
            }
            if (ret.type == 'right') {
                if(app.confirm_btn){
                    scan();
                }else{
                    return
                }
               
            }
        });
        api.addEventListener({
            name: 'keyback',
            extra: {
                slidBackIntercept: true    
            }
        }, function (ret, err) {
            if(app.confirm_btn){
                close_win1()  
            }else{
                close_win()
            }   

        });
        api.addEventListener({
            name: 'sn_job_issue'
        }, function (ret, err) {
            if(ret && ret.value){
                var snposts = ret.value;
                app.list[snposts.index].OnhandQty = snposts.OnhandQty;
                app.list[snposts.index].SerialNum = snposts.SerialNum;
                console.log(JSON.stringify(app.list),44444)
                api.closeWin({name: 'sn_job_issue'});
            }
        });


    }
    
    function close_win1() {
        console.log(111111)
        var msg = app.confirm_btn ? lan['issue_cancel_tips'] : lan['issue_cancel_tips'];
        if (app.confirm_btn && app.list.length != 0) {
            api.confirm({
                title: lan['Tips'],
                msg: msg,
                buttons: [lan['NO'], lan['YES'], lan['Cancel']]
            }, function (ret, err) {
                var index = ret.buttonIndex;
                if (index == 2) {
                    checksubmit();
                } else if (index == 1) {
                    close_win();
                }
            });
        }else{
            close_win();
        }


    }
    function checksubmit() {
        let hasNegativeQty = false;

        for (let i = 0; i < app.list.length; i++) {

            if(app.list[i].Part_TrackSerialNum && app.list[i].SerialNum.length == 0){
                api.toast({  
                    msg: lan['Serialnum_placeholder'],  
                    location: 'middle'  
                });
                return
            }
            if(app.list[i].Part_TrackLots && !app.list[i].LotNum){
                api.toast({  
                    msg: 'LotNum is required',  
                    location: 'middle'  
                });
                return
            }
            if(!app.list[i].OnhandQty){
                api.toast({  
                    msg: 'Quantity is required',  
                    location: 'middle'  
                });
                return
            }
            const item = app.list[i];
            if (item.PartClass_NegQtyAction === "Stop") {
                if (processNumber(item.OnhandQty,item.NumOfDec) > processNumber(item.MaxQty,item.NumOfDec)) {
                    const message = `Part: ${item.PartNum}. Warehouse: ${item.WareHouseCode}. Bin: ${item.BinNum}. This transaction will result in a negative onhand quantity for the bin.`;
                    api.confirm({
                        title: lan["Tips"],
                        msg: message,
                        buttons: ["", lan["YES"]],
                    },function (ret, err) {
                        // 用户点击了 "YES"，继续提交数据或执行相应的操作
                        // 在这里编写用户点击 "YES" 后的处理逻辑
                        });
                    hasNegativeQty = true;
                    break; // 提示一次后停止继续检查
                }
            }
        }

        if (!hasNegativeQty) {
            for (let i = 0; i < app.list.length; i++) {
                const item = app.list[i];
                if (item.PartClass_NegQtyAction === "Warn" ) {
                    if (processNumber(item.OnhandQty,item.NumOfDec) > processNumber(item.MaxQty,item.NumOfDec)) {
                        const message = `This transaction will result in a negative onhand quantity for Part: ${item.PartNum}, Bin: ${item.BinNum}. Do you want to continue?`;
                        api.confirm(
                        {
                            title: lan["Tips"],
                            msg: message,
                            buttons: [lan["NO"], lan["YES"], lan["Cancel"]],
                        },
                        function (ret, err) {
                            var index = ret.buttonIndex;
                            if (index === 2) {
                                submitfrom();
                                // 用户点击了 "YES"，继续提交数据或执行相应的操作
                                // 在这里编写用户点击 "YES" 后的处理逻辑
                            } else if (index === 1) {
                                close_win();
                                // 用户点击了 "NO"，返回原页面或执行相应的操作
                                // 在这里编写用户点击 "NO" 后的处理逻辑
                            }
                        }
                        );
                        return; // 提示一次后停止继续检查
                    }
                }
            }

            submitfrom();
        }
    }

    function close(){
        app.confirm_btn = false;
        api.closeWin({})
    }
    function scan1(item,index){
        var FNScanner = api.require('FNScanner');
        FNScanner.open({
            autorotation: true
        }, function (ret, err) {
            console_debug(ret, err);
            if (ret) {
                if (ret.eventType == 'success') {
                    app.$set(app.$data.list[index],'LotNum',ret.content)
                    setTimeout(function(){
                        onHandData(item,index)
                    },300)
                }
            } 
        });
          
    }
    function scan2(item,index){
        var FNScanner = api.require('FNScanner');
        FNScanner.open({
            autorotation: true
        }, function (ret, err) {
            console_debug(ret, err);
            if (ret) {
                if (ret.eventType == 'success') {
                    app.$set(app.$data.list[index],'WareHouseCode',ret.content)
                    setTimeout(function(){
                        loadBinData(item,index)
                    },300)
                }
            } 
        });
          
    }
    function scan3(item,index){
        var FNScanner = api.require('FNScanner');
        FNScanner.open({
            autorotation: true
        }, function (ret, err) {
            console_debug(ret, err);
            if (ret) {
                if (ret.eventType == 'success') {
                    app.$set(app.$data.list[index],'BinNum',ret.content)
                    setTimeout(function(){
                        onHandData(item,index)
                    },300)
                }
            } 
        });
          
    }

    async function loadWarehouseCodeData(item,i) {
        userinfo = get_user_info();
        if (!userinfo.Token) {
            return;
        }
        $('.myselect3').selectpicker('destroy'); // 先销毁
        await api.ajax({
            url: server + 'BaqSvc/WMS_WarehouseForPart/?CompID=' + userinfo.Company + "&Site=" + userinfo.Site +"&PartNum="+item.PartNum,
            method: 'get',
            returnAll: false,
            headers: {
                'Authorization': userinfo.Token,
            },
            data: {}
        }, function (ret, err) {
            if (ret && ret.value.length > 0) {
                app.$set(app.$data.list[i],'WareHouseCodeList',ret.value)
                setTimeout(function () {
                    $('.myselect3').selectpicker('refresh');//在更新
                }, 200)
                console.log(JSON.stringify(app.list[i].WareHouseCodeList), 22222)
            }
        });
    }
    async function loadBinData(item,i) {
        userinfo = get_user_info();
        $('.myselect4').selectpicker('destroy'); // 先销毁
        await api.ajax({
            url: server + 'BaqSvc/WMS_WhseBin/?CompID=' + userinfo.Company + "&WarehouseCode=" + item.WareHouseCode,
            method: 'get',
            returnAll: false,
            headers: {
                'Authorization': userinfo.Token,
            },
            data: {

            }
        }, function (ret, err) {
            if (ret && ret.value.length > 0) {
                app.$set(app.$data.list[i],'BinNumList',ret.value)
                setTimeout(function () {
                    $('.myselect4').selectpicker('refresh');//在更新
                }, 200)
                console.log(JSON.stringify(app.list[i].BinNumList), 22222)
            }

        });
    }
    function init_list(data) {
        for (i in data) {
            data[i].PartNum = data[i].Part_PartNum;
            data[i].PartDescription = data[i].Part_PartDescription
            data[i].IUM = data[i].Part_IUM;
            data[i].OnhandQty = "";
            data[i].MaxQty = "";
            data[i].LotNum = "";
            data[i].SerialNum = [];
            data[i].WareHouseCodeList = [];
            data[i].BinNumList = [];
            data[i].WareHouseCode = data[i].PlantConfCtrl_DefaultWhse;
            data[i].BinNum = data[i].PlantConfCtrl_DefGenBin;
            data[i].AllowDecimals = data[i].UOM_AllowDecimals;
            data[i].NumOfDec = data[i].UOM_NumOfDec
            data[i].warehouseFlag=false;
            data[i].binFlag=false;
            data[i].lotFlag=false;
        }
        return data;
    }
    function init_select2() {
        var cls = 'js-data-example-ajax';
        var id = 'exampleModal';
        if (document.body.clientWidth > 576) {
            cls = 'js-data-example-ajax2';
            id = 'exampleModal2';
        }
        $('.' + cls).select2({
            theme: 'bootstrap4',
            width: '100%',
            placeholder: lan['REASON_CODE_placeholder'],
            dropdownParent: $('#' + id),
            allowClear: Boolean($(this).data('allow-clear')),
            ajax: {
                transport: function (params, success, failure) { // this function works correctly 


                    var filter = "Company eq '" + userinfo.Company + "' and ReasonType eq 'M' ";
                    if (params.data.term && params.data.term != '') {
                        filter += " and Description ge '" + params.data.term + "'";
                    }
                    console_debug(filter, params);

                    api.ajax({
                        url: server + 'Erp.BO.ReasonSvc/List/',
                        method: 'get',
                        returnAll: false,
                        headers: {
                            'Authorization': userinfo.Token,
                        },
                        data: {
                            values: {
                                '$select': 'ReasonCode,Description,Company',
                                '$filter': filter
                            }
                        }
                    }, function (ret, err) {
                        console_debug(ret, err);
                        if (ret) {
                            success(ret);
                        } else {
                            failure();
                        }

                    });
                },
                processResults: function (data, params) {
                    console_debug(data, params);
                    var rows = [];
                    for (i in data.value) {
                        var row = {};
                        row.id = data.value[i].ReasonCode;
                        row.text = data.value[i].Description;
                        rows.push(row);
                    }
                    return {
                        results: rows,
                        pagination: {
                            more: false
                        }
                    };
                },
            }
        });

        $('.' + cls).on('select2:select', function (e) {
            var data = e.params.data;
            console_debug(data, '');
            app.searchdata.ReasonCode = data.id;
        });
    }

    function scan() {

        var FNScanner = api.require('FNScanner');
        FNScanner.open({
            autorotation: true
        }, function (ret, err) {
            console_debug(ret, err);
            if (ret) {
                if (ret.eventType == 'success') {
                    loadqrData(ret.content)
                }

            } else {
                //alert(JSON.stringify(err));
            }
        });
    }

    function loadqrData(data) {

        userinfo = get_user_info();
        var filter = "?CompID=" + userinfo.Company  + "&Site=" + userinfo.Site;
        filter += "&PartNum=" + data ;
        api.ajax({
            url: server + 'BaqSvc/WMS_PartInfo/' + filter,
            method: 'get',
            returnAll: false,
            headers: {
                'Authorization': userinfo.Token,
            },
            data: {}  
        }, function (ret, err) {
            ajaxing = 0;
            is_scan = 0;
            console.log(JSON.stringify(ret),44444)
            hideProgress();
            if (ret && ret.value.length>0) {
                
                let newList = init_list(ret.value)
                for (i in newList) {
                    var ret1 = [];
                    ret1.push(newList[i]);
                    var res = check_repeat(ret1[0]);
                    //alert(res);
                    if (res == 1) {
                        api.toast({
                            msg: lan['Carton_Label_exists'],
                            location: 'middle'
                        });
                        return false;
                    }
                    app.list = app.list.concat(ret1);
                    setTimeout(function(){
                        for(let i in app.list){
                            onHandData(app.list[i],i) 
                            loadWarehouseCodeData(app.list[i],i)
                            loadBinData(app.list[i],i)
                        }
                        console.log(JSON.stringify(app.list),55555)  
                    },200)
                    
                    if (app.list.length > 0) {
                        app.receipt_btn = false;
                        
                    }
                }

            }else{
                api.toast({
                    msg: lan['Part_valid_placeholder'],
                    location: 'middle'
                });
            }

        });
    }
    function onHandData(data,i){
        const bacth =localStorage.getItem('batch')
        if(bacth == 0){
            firstOnhandData(data,i)
        }else{
            loadOnhandData(data,i)
        }
    }
    function firstOnhandData(data,i){
        userinfo = get_user_info();
        var filter = "?CompID=" + userinfo.Company;
        filter += "&PartNum=" + data.PartNum;
        filter += "&RowNum=" + app.RowNum;
        console.log(filter,22222)
        api.ajax({
            url: server + 'BaqSvc/WMS_FirstLot/' + filter,
            method: 'get',
            returnAll: false,
            headers: {
                'Authorization': userinfo.Token,
            },
            data: {}  
        }, function (ret, err) {
            ajaxing = 0;
            is_scan = 0;
            console.log(JSON.stringify(ret),66666)
            hideProgress();
            if (ret && ret.value.length>0) {
                app.$set(app.$data.list[i],'MaxQty',processNumber(ret.value[0].PartBin_OnhandQty,data.NumOfDec))
                app.$set(app.$data.list[i],'LotNum',ret.value[0].PartBin_LotNum)
            }
        })
    }

   function loadOnhandData(data,i){
        userinfo = get_user_info();
        var filter = "?CompID=" + userinfo.Company  + "&Site=" + userinfo.Site;
        filter += "&PartNum=" + data.PartNum;
        filter += "&WhseCode=" + data.WareHouseCode;
        filter += "&Bin=" + data.BinNum;
        if(data.LotNum){
            filter += "&LotNum=" + data.LotNum;
        }
        console.log(filter,77777)
        api.ajax({
            url: server + 'BaqSvc/WMS_PartBinOnhand/' + filter,
            method: 'get',
            returnAll: false,
            headers: {
                'Authorization': userinfo.Token,
            },
            data: {}  
        }, function (ret, err) {
            ajaxing = 0;
            is_scan = 0;
            console.log(JSON.stringify(ret),66666)
            hideProgress();
            if (ret && ret.value.length>0) {
                app.$set(app.$data.list[i],'MaxQty',processNumber(ret.value[0].PartBin_OnhandQty,data.NumOfDec))  
            }
        })
    }    
    function check_repeat(data) {
        var res = 0;
        for (i in app.list) {
            if (data.Part_PartNum == app.list[i].Part_PartNum) {
                res = 1;
            }
        }
        return res;
    }

  
    function submitfrom() {

        if (app.searchdata.ReasonCode == '') {
            api.toast({
                msg: lan['REASON_CODE_placeholder'],
                location: 'middle'
            });
            return;
        }
        postlist = [];
        for (i in app.list) {
            var arr = [];
           
            if(app.list[i].SerialNum){
                if(app.list[i].SerialNum.length>0){
                    var SerialNum = app.list[i].SerialNum;
                    for(k in SerialNum){
                        var row1 = {};
                        row1.SerialNumber = SerialNum[k].SerialNumber;
                        arr.push(row1);
                    }
                }
            }
            if(arr.length){
                app.list[i].SelectedSerialNumbers = arr;
            }

            postlist.push(app.list[i]);
            
        }
        console.log(JSON.stringify(postlist),3333333)
        if (!postlist) {
            api.toast({
                msg: lan['No_Data_Submit'],
                location: 'middle'
            });
            return;
        }

        var datalist = {};
        for (i in postlist) {
            //var item = postlist[i]
            var item = get_new_arr(postlist[i]);
            var key = item.PartNum + item.Company + item.WarehouseCode + item.BinNum + item.LotNum;
            if (datalist[key]) {
                datalist[key].OnhandQty = datalist[key].OnhandQty + item.OnhandQty;
                if (datalist[key].SelectedSerialNumbers) {
                    datalist[key].SelectedSerialNumbers = datalist[key].SelectedSerialNumbers.concat(item.SelectedSerialNumbers);
                } else {
                    datalist[key].SelectedSerialNumbers = item.SelectedSerialNumbers;
                }
            } else {
                datalist[key] = item;
            }
        }
        var postrows = [];
        for (key in datalist) {
            postrows.push(datalist[key]);
        }




        postcount = postrows.length;
        returncount = 0;
        tagspostcount = 0;
        console.log(JSON.stringify(postrows),4444444)
        if(ajaxing){return;}showProgress(lan['Loading']);
        for (i in postrows) {
            submit_issuemisc(postrows[i]);
        }

    }
    function resetfrom(){
        app.list = [];
        app.confirm_btn = false;
        app.receipt_btn = true;
        app.snsCheck = false;
        app.Lot_btn = false;
        $('.myselect3').selectpicker('refresh'); // 先销毁
        $('.myselect4').selectpicker('refresh'); // 先销毁
    }

    function submit_issuemisc(item) {

        var data1 = {
            "CompanyID": userinfo.Company,
            "PlantID": userinfo.Site,
            "UserName": userinfo.Name,
            "Password": userinfo.password,
            "TranDate": app.searchdata.ArrivedDate,
            "PartNum": item.PartNum,
            "WarehouseCode": item.WareHouseCode,
            "BinNum": item.BinNum,
            "TranQty": item.OnhandQty,
            "UM": item.IUM,
            "ReasonCode": app.searchdata.ReasonCode,
            "LotNum": item.LotNum,
        }
        if(item.SelectedSerialNumbers){
            data1.SelectedSerialNumbers = item.SelectedSerialNumbers
        }
        console.log(JSON.stringify(data1),55555555)

        api.ajax({
            url: wmsserver + 'issuemisc/',
            method: 'post',
            returnAll: false,
            headers: {
                'token': wmstoken,
                'Content-Type': 'application/json;charset=utf-8'
            },
            data: {
                body: create_submit_data(data1)
            }
        }, function (ret, err) {
            ajaxing = 0;
            console_debug(ret, err);
            returncount++;
            if (ret && ret.code == 1) {
                if (returncount == postcount) {
                    api.alert({
                        title: lan['Tips'],
                        msg: lan['Submitted_successfully']
                    }, function (ret, err) {
                        app.confirm_btn = false;
                        app.receipt_btn = true;
                        app.snsCheck = true;
                        app.Lot_btn = true;
                        app.RowNum  = 1
                        $('.myselect3').selectpicker('destroy'); // 先销毁
                        $('.myselect4').selectpicker('destroy'); // 先销毁
                        setTimeout(function(){
                            $('.myselect5').selectpicker('refresh');//在更新
                        },200)
                    });

                    hideProgress();
                }
            } else {
                app.receipt_btn = true
                hideProgress();
                errMassage(ret.msg)
            }

        });
    }

</script>

</html>